package com.example.telesys.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.spring.webflux.exception.SentinelBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来处理到底是因为什么规则 而抛出的异常
 * 是熔断降级 还是流量控制 还是授权控制呢 还是热点规则呢
 */
//@Component
public class SentinelExceptionHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        //设置写回页面的内容编码信息
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResponseData data = null;
        if(e instanceof FlowException){
            data = new ResponseData(-1, "抱歉，该接口已被限流！");
        }else if(e instanceof DegradeException){
            data = new ResponseData(-2, "抱歉，该接口已被熔断降级！");
        }
        //写回JSON字符串到前端
        httpServletResponse.getWriter().write(JSON.toJSONString(data));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class ResponseData{
        private Integer code;
        private String message;
    }
}
